package com.study.blog.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class CopyUtil {

    /**
     * 单体复制
     *
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T copy(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }

        T obj = null;

        try {
            obj = clazz.newInstance(); // 生成一个实例

        } catch (Exception e) {
            e.printStackTrace();
        }

        BeanUtils.copyProperties(source, obj);

        return obj;
    }


    public static <T> T copyList(List source, Class<T> clazz) {

        List<T> target = new ArrayList<>();

        if (!CollectionUtils.isEmpty(source)) {
            for (Object c : source) {
                T obj = copy(c, clazz);
                target.add(obj);

            }
        }
        return (T) target;
    }
}
